/**
 * Copyright (c) 2016-2020 https://github.com/zhaohuatai
 *
 * contact z_huatai@qq.com
 *  
 */
package org.zfes.snowy.auth.biz.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zfes.snowy.auth.biz.dao.AuthRoleMapper;
import org.zfes.snowy.auth.biz.model.AuthRole;
import org.zfes.snowy.auth.biz.service.IAuthRoleService;
import org.zfes.snowy.auth.shiro.event.AuthCacheClearType;
import org.zfes.snowy.auth.shiro.event.AuthChangeEvent;
import org.zfes.snowy.core.data.DataSet;
import org.zfes.snowy.core.data.ComboboVo;
import org.zfes.snowy.core.idcenter.IDGenerator;
import org.zfes.snowy.base.dao.params.ParamMap;
import org.zfes.snowy.core.util.ZAlert;
import org.zfes.snowy.core.util.ZAssert;
import org.zfes.snowy.core.util.ZBeanUtil;
import org.zfes.snowy.core.util.ZObjectUtil;
import org.zfes.snowy.core.util.ZStrUtil;
@Service
@Lazy(true)
public class AuthRoleServiceImpl implements IAuthRoleService{
	@Autowired
	private AuthRoleMapper authRoleMapper;
	@Autowired  
	private  ApplicationEventPublisher publisher;
	@Transactional(rollbackFor=Exception.class)
	public	void creatAuthRole(AuthRole authRole){
		ZBeanUtil.validateBean(authRole);
		AuthRole role_1=authRoleMapper.selectAuthRoleByCode(authRole.getRoleCode());
		if(role_1!=null){
			ZAlert.Error("该角色编码已经存在");
		}
		authRole.setId(IDGenerator.genLongId());
		authRoleMapper.insertSelective(authRole);
	}
	
	@Transactional(rollbackFor=Exception.class)
	@Override
	public void updateAuthRole(AuthRole authRole) {
		ZBeanUtil.validateBean(authRole);
		AuthRole role_1=authRoleMapper.selectAuthRoleByCode(authRole.getRoleCode());
		if(!ZObjectUtil.isEmpty(role_1) &&(!(role_1.getId().equals(authRole.getId())))){
			ZAlert.Error("该角色编码已经存在");
		}
		authRoleMapper.updateByPrimaryKeySelective(authRole);
		this.publisher.publishEvent(new AuthChangeEvent(SecurityUtils.getSubject(),AuthCacheClearType.cachedAuthorizationInfoByRole,authRole.getRoleCode()));  
	}
	
	
	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public Optional<AuthRole> loadAuthRole(Long id) {
		if(id!=null){
			return Optional.ofNullable(authRoleMapper.selectByPrimaryKey(id));
		}
		return Optional.empty();
	}
	 public Optional<AuthRole> loadAuthRoleByCode(String roleCode){
		 if(ZStrUtil.hasText(roleCode)){
			 return Optional.ofNullable(authRoleMapper.selectAuthRoleByCode(roleCode));
		 }
		 return Optional.empty();
	 }
	@Override
	public void deleteAuthRole(Long id) {
		ZAssert.notNull(id, "请选择要删除的数据");
		AuthRole authRole=authRoleMapper.selectByPrimaryKey(id);
		ZAssert.notNull(authRole, "未查到角色数据");
		authRoleMapper.deleteByPrimaryKey(id);
		this.publisher.publishEvent(new AuthChangeEvent(SecurityUtils.getSubject(),AuthCacheClearType.cachedAuthorizationInfoByRole,authRole.getRoleCode()));  
		
	}
	
//	@Transactional(rollbackFor=Exception.class)
//	@Override
//	public void batchDeleteAuthRole(List<Long> ids) {
//		ZAssert.notEmpty(ids, "请选择数据");
//		authRoleMapper.batchDeleteAuthRole(ids);
//	}
	
	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public DataSet loadAuthRoleList(String appKey,Map<String,Object> params) {
		ParamMap pm=ParamMap.filterParam(params);
		pm.getStr("name").ifPresent(v->pm.updateParam( "name", "%"+v+"%"));
		pm.getStr("roleCode").ifPresent(v->pm.updateParam( "roleCode", "%"+v+"%"));
		pm.getBoolean("enabled").ifPresent(v->pm.updateParam( "enabled", v));
		pm.updateParam("appKey", appKey);
		DataSet ds=DataSet.newDS(authRoleMapper.selectAuthRoleListCount(pm), authRoleMapper.selectAuthRoleList(pm));
		return ds;
	}
	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public List<ComboboVo> loadRoleComboboVo(String appKey,Boolean firstEmpty) {
		if(ZStrUtil.hasNoText(appKey)){
			return Collections.emptyList();
		}
		List<ComboboVo> roleList=authRoleMapper.selectComboboVo(appKey);
		 List<ComboboVo> roleList2=new ArrayList<>();
		 if(firstEmpty!=null&&firstEmpty){
			 roleList2.add(0, ComboboVo.newEmptyFirst()); 
		 }
		 roleList2.addAll(roleList);
		 
		return roleList2;
	}

	@Transactional(rollbackFor=Exception.class,readOnly=true)
	@Override
	public List<ComboboVo> loadRoleComboboVo2(Boolean firstEmpty) {
		List<ComboboVo> roleList=authRoleMapper.selectComboboVo(null);
		List<ComboboVo> roleList2=new ArrayList<>();
		if(firstEmpty!=null&&firstEmpty){
			roleList2.add(0, ComboboVo.newEmptyFirst());
		}
		roleList2.addAll(roleList);

		return roleList2;
	}

	@Transactional(rollbackFor=Exception.class,readOnly=false)
	@Override
	public void setAuthRoleEnabled(List<Long> ids, Boolean enabled){
		ZAssert.notEmpty(ids, "请选择数据");;
		ZAssert.notNull(enabled, "状态参数");
		List<AuthRole>  roleList=authRoleMapper.selectByIds(ids);
		authRoleMapper.updateEnabled(ids,enabled);
		if(ZObjectUtil.isNotEmpty(roleList)) {
			roleList.forEach(val->{
				this.publisher.publishEvent(new AuthChangeEvent(SecurityUtils.getSubject(),AuthCacheClearType.cachedAuthorizationInfoByRole,val.getRoleCode()));  
			});
		}
		
	}
}
